package com.zline.foodraise.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.JsResourceBean;
import com.zline.foodraise.js.HostJSScope;
import com.zline.foodraise.js.MyWebViewSetting;
import com.zline.foodraise.listener.CanChildScrollUpCallback;
import com.zline.foodraise.listener.JsInvokeListener;
import com.zline.foodraise.ui.activity.BannerActivity_;
import com.zline.foodraise.ui.activity.PersonalHomePageActivity_;
import com.zline.foodraise.ui.activity.ProjectDetailActivity_;
import com.zline.foodraise.ui.activity.SetAddrActivity_;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.URLUtils;
import com.zline.foodraise.view.ScrollSwipeRefreshLayout;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/6/25.
 * 首页
 */
@EFragment(R.layout.fragment_web)
public class HomePageFragment extends Fragment implements JsInvokeListener,CanChildScrollUpCallback{
    private static final String LOG_TAG = HomePageFragment.class.getSimpleName();
    Context cxt;
    @ViewById(R.id.fragment_wv)
    WebView wv;
    @ViewById(R.id.fragment_web_srl)
    ScrollSwipeRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    MyWebViewSetting mSetting;
    @Pref
    AppPref_ appPref;
    @Bean
    HostJSScope hostJSScope;
    @Bean
    URLUtils urlUtils;
    //点击重试
    boolean isReLoad=false;
    //加载出错
    boolean isErro=false;
    boolean logout=false;

    @AfterInject
    void doSomeAfterInject() {
        cxt = getActivity();
    }

    @AfterViews
    void doSomeAfterViews() {
        initWebView();
        initSwipRefreshLayout();
    }

    void initWebView() {
        mSetting = new MyWebViewSetting(wv, cxt);
        mSetting.setWebView();
        hostJSScope.setJsInvokeListener(this);
        String url = appPref.rootUrl().get() + Constant.HOME_PAGE_URL;
        wv.loadUrl(url);
        wv.setWebViewClient(new WebViewClient() {
            //出错界面
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                showErroView();
                LUtil.i(LOG_TAG, "______________erroCode________" + description);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LUtil.i(LOG_TAG, "_________shouldOverrideUrlLoading________" + url);
                doLinkUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                LUtil.i(LOG_TAG, "_________onPageStarted________" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LUtil.i(LOG_TAG, "____Host_____onPageFinished________" + url);
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }

                if (isReLoad && !isErro) {
                    exception_fl.setVisibility(View.GONE);
                    exception_rl.setVisibility(View.GONE);
                    wv.setVisibility(View.VISIBLE);
                }
                isErro = false;
                isReLoad = false;

                //退出登录后清除用户信息
                if (logout) {
                    wv.loadUrl("javascript:clearUserInfo()");
                    logout = false;
                }

                stopRefresh();
            }
        });


    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setCanChildScrollUpCallback(this);
        swipeRefreshLayout.setEnabled(false);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                wv.reload();
            }
        });
    }

    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @OnActivityResult(Constant.HOME_PAGE_FRAGMENT_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data, @OnActivityResult.Extra String value) {
        switch (resultCode) {
            case Constant.ADDR_SET_RESULT_CODE:
                wv.loadUrl("javascript:choicedAddress(" + value + ")");
                wv.reload();
                break;
            default:
                break;
        }
    }

    //显示网页加载出错情况
    void showErroView(){
        isErro=true;
        exception_fl.setVisibility(View.VISIBLE);
        exception_rl.setVisibility(View.VISIBLE);
        wv.setVisibility(View.GONE);
    }

    //登录成功后上报状态
    public void setUserInfo() {
        double latPoint = Double.parseDouble(appPref.latPoint().get());
        double lonPoint = Double.parseDouble(appPref.lonPoint().get());
        long userId = appPref.userId().get();
        long cityId = appPref.cityId().get();
        String cityName = appPref.city().get();
        String userAddress = appPref.userAddress().get();
        String token = appPref.token().get();
        LUtil.i(LOG_TAG, "___setUserInfo_____返回___" + token + "________addr" + userAddress);
        wv.loadUrl("javascript:getUserInfo('" + latPoint + "','" + lonPoint + "','" + userId + "','" + cityId +
                "','" + cityName + "','" + userAddress + "','" + token + "')");
    }

    //退出登录后通知用户
    public void clearUserInfo(){
        logout=true;
    }



    //处理带跳转链接的url
    void doLinkUrl(String url) {
        String goal = urlUtils.getUrlJumpTo(url);
        String title = urlUtils.getUrlTitle(url);
        if (goal.equals("zc-detail")) {//跳转到筹详情页面
            ProjectDetailActivity_.intent(cxt).url(url).title(title).start();
        }else if(goal.equals("zc-list")){//筹列表页面加载失败时重新加载
            wv.loadUrl(url);
        } else {
            BannerActivity_.intent(cxt).url(url).start();
        }

    }

    //设置地址
    @Override
    public void jsInvoke(int flag) {
        switch (flag){
            case Constant.WEB_SET_ADDR:
                Intent intent = new Intent(cxt, SetAddrActivity_.class);
                startActivityForResult(intent, Constant.HOME_PAGE_FRAGMENT_REQUEST_CODE);
                break;
            default:
                break;
        }
    }

    @Override
    public void jsInvoke(int flag, JSONObject jsonObject) {
        switch (flag) {
            case Constant.WEB_PROFILE_FLAG:
                //启动其他人profile页
                gotoProfile(jsonObject);
                break;
            default:
                break;
        }

    }

    //启动个人Profile页
    void gotoProfile(JSONObject jsonObject) {
        String info = jsonObject.toString();
        Gson gson = new Gson();
        JsResourceBean jsResourceBean = gson.fromJson(info, JsResourceBean.class);
        if (jsResourceBean == null) return;
        PersonalHomePageActivity_.intent(this).userId(jsResourceBean.getUserId()).start();
    }

    @Override
    public void jsInvoke(double marginTop) {

    }

    @Override
    public void onResume() {
        super.onResume();
        hostJSScope.setJsInvokeListener(this);
        StatService.onResume(this);
        StatService.onPageStart(cxt, Constant.RAISE_LIST);
    }

    @Override
    public void onPause() {
        super.onPause();
        hostJSScope.setJsInvokeListener(null);
        logout=false;
        StatService.onPause(this);
        StatService.onPageEnd(cxt, Constant.RAISE_LIST);
    }

    @Click(R.id.reload_tv)
    void onClick(){
        isReLoad=true;
        wv.reload();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        return wv.getScrollY()>Constant.WEBVIEW_SCROLL_Y;
    }
}
